package com.xwaf.platform.system.provider.serviceimpl.mqtt;

import javax.annotation.PostConstruct;

import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xwaf.platform.system.api.service.mqtt.MqttService;

@Service(value = "mqttService")
public class MqttServiceImpl implements MqttService {

	private static final Logger logger = LoggerFactory.getLogger(MqttServiceImpl.class);

	@Autowired
	private MqttClient mqttClient;

	private String topics = "test/#";

	@PostConstruct
	public void onSub() {
		try {
			mqttClient.subscribe(topics, new IMqttMessageListener() {
				@Override
				public void messageArrived(String topic, MqttMessage message) throws Exception {
					logger.info(topic);
					logger.info(new String(message.getPayload()));
				}
			});
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void sendMessage(String topic, String message) {
		try {
			mqttClient.publish(topic, message.getBytes(), 1, false);
			logger.info("发送消息成功:{},{}", topic, message);
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}
}
